<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 商品服务
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Service\Goods;

use App\Models\Goods\GoodsSale;

use App\Models\Goods\GoodsStore;

use App\Models\ConfigureFunction;

use App\Models\Goods\GoodsPicture;

use App\Models\Promotion\PromotionMaster;

use App\Models\Goods\GoodsMarktingStrategy;

use Illuminate\Support\Facades\Redis as Redis;

class GoodsService
{
    
    public static function getGoodsSpecCache($id)
    {
        
    }

    /**
     * 查询商品详情缓存信息
     * @param array $parameter 查询条件
     * $parameter = [
     *      'id' => '商品id',
     *      'store_id' => '门店id',
     *      'search_promotion' => '是否需要查询商品促销活动，不传参数或参数值不等于0，则查询',
     *      'search_store' => '是否需要查询商品库存数据，不传参数或参数值不等于0，则查询',
     *      'search_marketing_strategy' => '是否查询商品营销策略，不传参数或参数值不等于0，则查询',
     * ];
     * @return array|string
     */
    public function getSaleCache($parameter = [])
    {

        //商品id
        if (!isset($parameter['id']) || !ebsig_is_int($parameter['id'])) {
            return [];
        }
        $id = $parameter['id'];

        //门店id
        if (!isset($parameter['store_id']) || !ebsig_is_int($parameter['store_id'])) {
            $store_id = 0;
        } else {
            $store_id = $parameter['store_id'];
        }

        //是否需要查询商品促销活动，默认查询
        if (!isset($parameter['search_promotion']) || $parameter['search_promotion'] !== 0) {
            $search_promotion = 1;
        } else {
            $search_promotion = 0;
        }

        //是否需要查询商品库存数据，默认查询
        if (!isset($parameter['search_store']) || $parameter['search_store'] !== 0) {
            $search_store = 1;
        } else {
            $search_store = 0;
        }

        //是否查询商品营销策略，默认查询
        if (!isset($parameter['search_marketing_strategy']) || $parameter['search_marketing_strategy'] !== 0) {
            $search_marketing_strategy = 1;
        } else {
            $search_marketing_strategy = 0;
        }

        //商品详情redis的key名称
        $redis_key = 'WDH_GOODS_SALE_' . $id;

        $goods = Redis::get($redis_key);
        if (!$goods) {

            //查询商品详情信息
            $goods_sale = GoodsSale::find($id);
            if( !$goods_sale ) {
                return [];
            }
            $goods = [
                'mid' => $goods_sale->mainPostID,
                'id' => $goods_sale->postID,
                'name' => $goods_sale->goodsName,
                'for_sale' => $goods_sale->forsale,
                'is_use' => $goods_sale->useFlg,
                'type' => $goods_sale->goodsType,
                'spec_id' => $goods_sale->specID,
                'spec' => $goods_sale->spec,
                'market_price' => $goods_sale->marketPrice,
                'sale_price' => $goods_sale->salePrice,
                'sale_points' => $goods_sale->salePoints,
                'pic' => $goods_sale->goodsMainPic,
                'barcode' => $goods_sale->barcode,
                'product_code' => $goods_sale->product_code,
                'product_spec' => $goods_sale->product_spec,
                'big_category_id' => $goods_sale->bigCategoryID,
                'mid_category_id' => $goods_sale->midCategoryID,
                'small_category_id' => $goods_sale->smallCategoryID,
            ];

            //查询商品图片
            $goods_pic = GoodsPicture::where('mainPostID', $goods_sale->mainPostID)->orderBy('sortOrder', 'asc')->get()->toArray();
            if ($goods_pic) {
                foreach ($goods_pic as &$pic) {
                    $goods['pic_list'][] = $pic['pictureLink'];
                }
            } else {
                $goods['pic_list'] = [];
            }

            Redis::set($redis_key, 3600, $goods);

        } else {
            $goods = json_encode($goods);
        }

        //根据门店查询商品营销策略
        if ($search_marketing_strategy && $store_id > 0) {
            $goods_marketing_strategy = $this->getMarketingStrategy($id, $store_id);
            if ($goods_marketing_strategy) {
                $goods['market_price'] = $goods_marketing_strategy['market_price'];
                $goods['sale_price'] = $goods_marketing_strategy['sale_price'];
                $goods['sale_points'] = $goods_marketing_strategy['sale_points'];
            }
        }

        //查询商品库存
        if ($search_store) {
            //是否开启门店选品，如果开启需要根据门店id查询库存数据
            $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall',1);
            if ( $is_choose_goods_by_mall ) {
                $goods['store'] = GoodsStore::search($goods['product_code'], $goods['product_spec'], $store_id );
            } else {
                $goods['store'] = GoodsStore::search($goods['product_code'], $goods['product_spec']);
            }
        } else {
            $goods['store'] = 0;
        }

        return $goods;

    }

    /**
     * 根据门店查询商品营销策略
     * @param int $id 商品网购号
     * @param int $store_id 门店id
     * @return array|mixed
     */
    public function getMarketingStrategy($id = 0, $store_id = 0)
    {

        if (!ebsig_is_int($id) || !ebsig_is_int($store_id)) {
            return [];
        }

        $marketing_strategy_key = 'WDH_GOODS_MARKETING_STRATEGY_' . $id . '_' . $store_id;
        $goods_marketing_strategy = Redis::get($marketing_strategy_key);
        if (!$goods_marketing_strategy) {

            $temp_goods_marketing_strategy = GoodsMarktingStrategy::where(['shop_id' => $store_id,'postID' => $id])->first();
            if (!$temp_goods_marketing_strategy) {
                return [];
            }

            $goods_marketing_strategy = [
                'market_price' => $goods_marketing_strategy->marketPrice,
                'sale_price' => $goods_marketing_strategy->salePrice,
                'sale_points' => $goods_marketing_strategy->salePoints,
            ];
            Redis::set($marketing_strategy_key, 3600, json_encode($goods_marketing_strategy));

        } else {
            $goods_marketing_strategy = json_decode($goods_marketing_strategy);
        }

        return $goods_marketing_strategy;

    }

    public function promotion($parameter = [])
    {

        //商品id
        if (!isset($parameter['id']) || !ebsig_is_int($parameter['id'])) {
            return [];
        }
        $id = $parameter['id'];

        //门店id
        if (!isset($parameter['user_id']) || !ebsig_is_int($parameter['user_id'])) {
            $user_id = 0;
        } else {
            $user_id = $parameter['user_id'];
        }

        //门店id
        if (!isset($parameter['store_id']) || !ebsig_is_int($parameter['store_id'])) {
            $store_id = 0;
        } else {
            $store_id = $parameter['store_id'];
        }

        //门店区域id
        if (!isset($parameter['store_area_id']) || !ebsig_is_int($parameter['store_area_id'])) {
            $store_area_id = 0;
        } else {
            $store_area_id = $parameter['store_area_id'];
        }

        //商品销售价
        if (!isset($parameter['sale_price']) || empty($parameter['sale_price'])) {
            $sale_price = 0;
        } else {
            $sale_price = $parameter['sale_price'];
        }

        //商品赠送积分
        if (!isset($parameter['sale_points']) || empty($parameter['sale_points'])) {
            $sale_points = 0;
        } else {
            $sale_points = $parameter['sale_points'];
        }

        //商品数量
        if (!isset($parameter['goods_amount']) || !ebsig_is_int($parameter['goods_amount'])) {
            $goods_amount = 1;
        } else {
            $goods_amount = $parameter['goods_amount'];
        }

        $platform = 0;

        //获取会员等级id
        $rank_id = 0;
        if ($user_id) {
            $customer  = Customer::select('rankID')->where('pcustID', $user_id)->first();
            if (!$customer) {
                $rank_id = $customer->rankID;
            }
        }

        //查询促销活动
        $now = date('Y-m-d H:i:s');
        $where = [
            [ 'start_time' , '<=' , $now],
            [ 'end_time' , '>=' , $now],
            [ 'useFlg' , '=' , 1]
        ];
        $goods_promotion = PromotionMaster::where($where)->orderBy('priority', 'desc')->get();
        if ( !$goods_promotion ) {
            return [];
        }

        $used_promotion_type = []; //已匹配的商品促销类型
        foreach ($goods_promotion as &$promotion) {

            if (isset($used_promotion_type[$promotion['promotion_type']])) {
                continue;
            }

            //促销扩展数据
            $promotion_extend = json_decode($promotion['promotion_json'], true);

            //部分商品
            if ($promotion_extend['selector_type'] == 2) { 
                if ($promotion_extend['selector_relation'] == 1) { //包含
                    if (!in_array($id, $promotion_extend['select_goods'])) {
                        continue;
                    }
                } else { //排斥
                    if (in_array($id, $promotion_extend['select_goods'])) {
                        continue;
                    }
                }
            }

            //检查会员等级
            if (isset($promotion_extend['cust_rank']) && !in_array($rank_id, $promotion_extend['cust_rank'])) {
                continue;
            }

            //筛选大区
            if (isset($promotion_extend['mallareaID']) && $store_area_id != $promotion_extend['mallareaID']) {
                continue;
            }


        }


    }

    public static function getCommentsCache($id)
    {
        
    }
    
    public static function getRandGoodsCache()
    {
        
        
        
    }
    

}